<template>
  <div class="app-container">
    <el-form
      ref="listFilterRef"
      :model="list.filter"
      inline
      class="list-filter"
    >
      <el-form-item prop="companyId">
        <KiSelect
          v-model="list.filter.companyId"
          placeholder="输入企业名称搜索"
          :search="getCompany"
          :options.sync="options.company"
          :props="{ value: 'companyId', label: 'companyName' }"
        />
      </el-form-item>
      <el-form-item prop="mapId">
        <KiSelect
          v-model="list.filter.mapId"
          placeholder="地图名称"
          :search="
            mapName =>
              new Promise(resolve =>
                $POST('sot-admin-api/scenic/map/listForSelect', {
                  mapName
                }).then(({ data }) => {
                  resolve(data)
                })
              )
          "
          :options.sync="options.map"
          :props="{ value: 'mapId', label: 'mapName' }"
        />
      </el-form-item>
      <el-button @click="reset">重置</el-button>
    </el-form>

    <div class="table-operation">
      <span>
        <el-button
          v-if="hasBtn['新增']"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="c"
        >
          新增
        </el-button>
      </span>
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column label="地图名称" prop="mapName" />
      <el-table-column label="所属企业" prop="companyName" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row: { mapId, status } }">
          <KiPopSwitch
            v-bind="popSwitchProps(status)"
            @change="updateStatus({ id: mapId, status: status ^ 1 })"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row: { mapId, status } }">
          <KiPopButton
            v-if="hasBtn['查看']"
            @click="r({ id: mapId }, 'config')"
          >
            查看
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['编辑']"
            @click="u({ id: mapId }, 'config')"
          >
            编辑
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['删除']" text="![#FF7575]"
            :elPopconfirmProps="{ title: '确认删除吗？' }"
            @click="d({ id: mapId })"
          >
            删除
          </KiPopButton>
        </template>
      </el-table-column>
    </el-table>

    <KiFormDialog
      :show.sync="form.show"
      :title="formTitle"
      v-model="form.data"
      :submit="submitForm"
      :readonly="form.status === 'r'"
      ref="formRef"
      :loading="form.loading"
    >
      <template #el-form>
        <el-form-item label="地图名称" prop="mapName" verify>
          <el-input
            v-model="form.data.mapName"
            placeholder="请输入地图名称"
            maxlength="30"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="选择企业" prop="companyId" verify>
          <KiSelect
            v-model="form.data.companyId"
            placeholder="输入企业名称搜索"
            :search="getCompany"
            :options.sync="options.company"
            :props="{ value: 'companyId', label: 'companyName' }"
          />
        </el-form-item>
        <el-form-item label="图片上传" prop="mapPath" verify>
          <Imgpond :count="1" v-model="form.data.mapPath" :size="20" :requestParam="{ original: true }"
            @change="onMapPathChange" />
          <el-button @click="$refs.HPMP.show(form.data.mapPath)" :disabled="form.status === 'r' || !form.data.mapPath">
            手绘地图量角器
          </el-button>
          <form-item-tip>
            在对齐地图时帮助你确定图片的旋转角度。测量好角度后，根据角度值重新上传图片。
          </form-item-tip>
        </el-form-item>
        <div style="border: 2px solid #409eff80;border-radius: 16px;padding: 16px;">
          <el-button type="primary" plain @click="showCoordPicker = true" style="margin: 16px 0 32px 0;"
            :disabled="form.status === 'r' || !form.data.mapPath">
            选择定位
          </el-button>
          <CoordPicker :show.sync="showCoordPicker" :lng.sync="form.data.__lng" :lat.sync="form.data.__lat"
            :rectangleImage="form.data.mapPath" :rectangle.sync="form.data.__rectangle" :rectangleCount="1"
            :mapOptions.sync="form.data.__mapOptions" @confirm="onCoordPickerConfirm" />
          <el-form-item label="中心点坐标" verify class="multiple">
            <el-form-item prop="location[0].longitude" verify :rules="rules.lng">
              <el-input v-model="form.data.location[0].longitude" placeholder="经度" clearable />
            </el-form-item>
            <el-form-item prop="location[0].latitude" verify :rules="rules.lat">
              <el-input v-model="form.data.location[0].latitude" placeholder="纬度" clearable />
            </el-form-item>
          </el-form-item>
          <el-form-item label="东北角坐标" verify class="multiple">
            <el-form-item prop="location[1].longitude" verify :rules="rules.lng">
              <el-input v-model="form.data.location[1].longitude" placeholder="经度" clearable />
            </el-form-item>
            <el-form-item prop="location[1].latitude" verify :rules="rules.lat">
              <el-input v-model="form.data.location[1].latitude" placeholder="纬度" clearable />
            </el-form-item>
          </el-form-item>
          <el-form-item label="西南角坐标" verify class="multiple">
            <el-form-item prop="location[2].longitude" verify :rules="rules.lng">
              <el-input v-model="form.data.location[2].longitude" placeholder="经度" clearable />
            </el-form-item>
            <el-form-item prop="location[2].latitude" verify :rules="rules.lat">
              <el-input v-model="form.data.location[2].latitude" placeholder="纬度" clearable />
            </el-form-item>
          </el-form-item>
          <el-form-item label="缩放比例" prop="__mapOptions.zoom" verify>
            <el-input-number v-model="form.data.__mapOptions.zoom" :min="3" :max="19" :precision="0" />
          </el-form-item>
        </div>
      </template>
    </KiFormDialog>

    <HandPaintedMapProtractor ref="HPMP" />
  </div>
</template>

<script>
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import rules from '@/utils/rules'
import HandPaintedMapProtractor from './components/HandPaintedMapProtractor.vue'

export default {
  mixins: [pageMixin],
  components: { HandPaintedMapProtractor },
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'sot-admin-api/scenic/map/',
      axiosConfig: {
        getList: {
          url: 'list'
        },
        d: {
          method: 'DELETE'
        },
        r: ({ id }) => ({
          url: 'queryMapInfoById/' + id,
          method: 'POST'
        })
      },
      form: {
        data: {
          __rectangle: null,
          __lng: null,
          __lat: null,
          __mapOptions: {
            zoom: 17
          },
          location: [{ type: 0 }, { type: 1 }, { type: 2 }]
        }
      }
    }, {
      afterRetrieve(res) {
        const { longitude: southwestLng, latitude: southwestLat } =
          res.data?.location?.[2] || {}
        const { longitude: northeastLng, latitude: northeastLat } =
          res.data?.location?.[1] || {}
        const { longitude, latitude } = res.data?.location?.[0] || {}
        this.form.data.__lng = longitude
        this.form.data.__lat = latitude
        if (
          res.data.mapPath &&
          this.$notEmpty(southwestLng) &&
          this.$notEmpty(southwestLat) &&
          this.$notEmpty(northeastLng) &&
          this.$notEmpty(northeastLng)
        ) {
          this.form.data.__rectangle = [
            {
              image: res.data.mapPath,
              southwest: { lng: southwestLng, lat: southwestLat },
              northeast: { lng: northeastLng, lat: northeastLat }
            }
          ]
        }
        this.form.data.__mapOptions = {
          zoom: res.data.zoom
        }
      }
    }),
  data () {
    return {
      rules,
      showCoordPicker: false,
      keyName: [],
      options: {
        company: [],
        map: []
      }
    }
  },
  watch: {
    'form.data.__mapOptions.zoom': {
      immediate: true,
      handler(n) {
        this.form.data.zoom = n
      }
    }
  },
  methods: {
    onMapPathChange() {
      this.form.data.__rectangle = null
      this.form.data.__lng = null
      this.form.data.__lat = null
      this.form.data.__mapOptions = {
        zoom: 17
      }
      this.form.data.location = [
        { type: 0, }, { type: 1, }, { type: 2, }
      ]
    },
    getCompany (companyName) {
      return new Promise(resolve =>
        this.$POST('sot-admin-api/sys/company/listForSelect', {
          companyName
        }).then(({ data }) => {
          resolve(data)
        })
      )
    },
    onCoordPickerConfirm () {
      const { image, southwest, northeast } =
        this.form.data.__rectangle?.[0] || {}
      const { lng: northeastLng, lat: northeastLat } = northeast || {}
      const { lng: southwestLng, lat: southwestLat } = southwest || {}
      //this.form.data.mapPath = image
      this.form.data.location = [
        {
          type: 0,
          longitude: this.form.data.__lng,
          latitude: this.form.data.__lat
        },
        {
          type: 1,
          longitude: northeastLng,
          latitude: northeastLat
        },
        {
          type: 2,
          longitude: southwestLng,
          latitude: southwestLat
        }
      ]
    },
  }
}
</script>

<style scoped lang="scss">
:deep(.el-form-item.multiple) {
  & > .el-form-item__content {
    display: flex;
    justify-content: space-between;

    &:before,
    &:after {
      display: none;
    }

    .el-form-item {
      flex: 1;

      &:first-of-type {
        margin: 0 16px 0 0;
      }
    }
  }
}
</style>
